/**
 * @author wangze
 * @date 2017-12-19 13:42.
 **/

(function () {
    var _bt = window.BT,
        _util = _bt.util,
        _dialog = _util.dialog,
        _config = _util.config,
        _sUrl = _config.url.style,
        _debug = _util.debug;
    var gridOpt = {
        url: _sUrl.list,
        formatters: {
            "commands": function (column, row) {
                return '<button class="btn btn-xs btn-purple command-edit" data-row-id="' + row.id + '">样式管理</button> ';
                // return '<button type="button" class="btn btn-xs btn-default command-edit" ><span class="icon-pencil"></span></button> ' +
                //     '<button type="button" class="btn btn-xs btn-default command-delete"><span class="icon-trash"></span></button>'
                //return '<span class="label label-success height-auto">启用</span>';
            }
        }
    };


    var page = {
        grid: null,
        init: function () {
            page.grid = new _bt.BGrid(gridOpt);
            page.bind();
        }

    };
    /**
     *编辑页面初始化
     */
    page.edit = {
        dialog: null,
        addValidateRule: function (tree) {
            page.edit.deleteValidateRule();
            $.validator.addMethod("treeRequired", function (value, element) {
                if (!tree) return true;
                var selectedNodes = tree.getCheckedNodes(true);
                return selectedNodes && selectedNodes.length > 0;
            }, "必选");

            /**
             * 样式唯一性
             */
            $.validator.addMethod("nameUnique", function (value, element) {

                var isSuccess = false;
                var successEvent = function (data) {
                    if (data && data.flag) {
                        isSuccess = true;
                    } else {
                        // _dialog.info('验证用户名重复失败');
                    }
                };
                //编辑的时候，如果用户名不变，则不校验用户名重复
                var originName = $(element).attr('data-origin-name');
                if (originName && value === originName) {
                    return this.optional(element) || true;
                }

                _util.ajax({
                    url: _sUrl.check,
                    type: 'get',
                    async: false,
                    data: {rolesName: value}
                }, successEvent);
                return this.optional(element) || isSuccess;

            }, "名称重复");

        },
        deleteValidateRule: function () {
            delete  $.validator.methods.treeRequired;
            delete  $.validator.messages.treeRequired;
        },
        addValidate: function (f, tree) {
            page.edit.addValidateRule(tree);
            var validateOpt = {
                rules: {
                    rolesName: {
                        required: true,
                        nameUnique: true
                    },
                    tree: {
                        treeRequired: true
                    }
                },
                messages: {
                    rolesName: {
                        required: '必填'
                    }
                },
                submitHandler: function (form) {
                    var successEvent = function (data) {
                        if (data && data.flag) {
                            _dialog.info('保存成功');
                            page.edit.hide();
                            page.grid.reload();
                        } else {
                            _dialog.info('保存失败');
                            _debug.info(data);
                        }
                    };
                    var data = $(form).serializeObject();
                    if(tree){
                        data.ids = page.edit.getTreeData(tree.getCheckedNodes(true));//获取tree上已经选择的节点
                    }
                    _util.jsonAjax({
                        url: _sUrl.save,
                        data: data
                    }, successEvent);
                }
            };
            return f.validate($.extend({}, _util.validate.default, validateOpt));
        },
        getTreeData: function (data) {
            var result = [];
            $.each(data, function (i, item) {
                result.push(item.id);
            });

            return result.join(',');
        },
        formatTreeData: function (data) {
            var result = [];
            $.each(data, function (i, item) {
                var obj = {};
                obj.id = item.id;
                obj.pId = item.parentid;
                obj.name = item.name;
                obj.checked = item.isChecked || false;
                obj.open = true;
                result.push(obj);
            });
            return result;
        },
        addTree: function (zNodes) {
            var setting = {
                check: {
                    enable: true,
                    chkboxType: {"Y": "ps", "N": "ps"}
                },
                data: {
                    simpleData: {
                        enable: true,
                        idKey: 'id',
                        pIdKey: 'pId',
                        rootPId: 0
                    }
                },
                callback: {
                    onCheck: function (event, treeId, treeNode) {
                        $('[name=tree]').blur();
                    }
                }
            };
            var tree = $.fn.zTree.init($("#treeDemo"), setting, zNodes);
            return tree;
        },
        loadData: function (id) {
            var $form = $('#form-edit');
            var editSuccessEvent = function (data) {
                if (!(data && data.flag)) {
                    _debug.log(data);
                    return;
                }
                data = data.data;
                if (!data) {
                    _debug.log('没有获取到数据');
                    return;
                }
                data.id = id;//获取单个样式 没有主键，所以这里添加一下
               var treeData = page.edit.formatTreeData(data.menus);
               //编辑状态不能修改
               $.each(treeData,function (i,item) {
                   treeData[i].chkDisabled=true;
               });
                page.edit.addTree(treeData);
                $form.bindForm(data);
                $('[name=rolesName]').attr('data-origin-name', data.rolesName);
                page.edit.addValidate($form, null);
            };
            var menuSuccessEvent = function (data) {
                if (!(data && data.flag)) {
                    _debug.log(data);
                    return;
                }
                data = data.data;
                if (!data) {
                    _debug.log('没有获取到数据');
                    return;
                }
                var treeData = page.edit.formatTreeData(data);
                var tree = page.edit.addTree(treeData);
                page.edit.addValidate($form, tree);
            };
            /**
             * 修改
             */
            if (id) {
                //如果是修改不能修改菜单
                //$('.form-group',$form).eq(1).hide();
                _util.ajax({
                    url: _sUrl.data,
                    type: 'get',
                    data: {id: id}
                }, editSuccessEvent);
            }
            /**
             * 新增，要获取菜单menu
             */
            else {
                _util.ajax({
                    url: _sUrl.menu,
                    type: 'get'
                }, menuSuccessEvent);
            }


        },
        show: function (title, id) {
            var m = _dialog.edit({
                message: $('#edit-template').html(),
                title: title
            }, {
                init: function () {
                    page.edit.loadData(id);
                    $('.modal-footer').css('text-align', 'center');
                },
                success: function () {
                    $('#form-edit').submit();
                    return false;
                }
            });

            page.edit.dialog = m;
            return m;
        },
        hide: function () {
            page.edit.dialog && page.edit.dialog.modal('hide');
        }

    };
    /**
     * 页面事件绑定
     */
    page.bind = function () {
        var showDialog = page.edit.show;
        var searchEvent = function () {
            page.grid.reload();
        };
        var addEvent = function () {
            showDialog('新增栏目样式');
        };
        var delEvent = function () {
            //选择数据
            var ids = page.grid.getSelections();
            if (ids.length === 0) {
                _dialog.warn('请选择一条数据');
                return;
            }

            _dialog.confirm('确定删除吗?', function () {
                _util.ajax({
                    type: 'get',
                    url: _sUrl.del,
                    data: {ids: ids.join(',')}
                }, function (data) {
                    if (data && data.flag) {
                        _dialog.info('删除成功');
                        page.grid.reload();
                    } else {
                        if (data.data) {
                            _dialog.warn(data.data + '正在使用中，不能删除');
                        } else {
                            _dialog.warn('删除失败');
                        }

                    }
                });
            });


        };

        $('#btn-search').on('click', searchEvent);
        $('#btn-add').on('click', addEvent);
        $('#btn-del').on('click', delEvent);

        /**
         * 绑定grid上的编辑事件
         */
        page.grid.on('loaded', function () {
            $('.command-edit').on('click', function () {
                var id = $(this).attr('data-row-id');
                page.edit.show('栏目样式管理', id);
                return false;
            });
        });
    };

    $(function () {
        page.init();
    });

})();